package com.kajespero.domain.summary.impl;

import java.util.ArrayList;
import java.util.Collection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.kajespero.dao.summary.impl.SummaryDAOImpl;
import com.kajespero.domain.commons.impl.AbstractReadWriteDomain;
import com.kajespero.domain.summary.SummaryDomain;
import com.kajespero.jdo.Criteria;
import com.kajespero.model.PageBean;
import com.kajespero.model.SummaryBean;

public class SummaryDomainImpl extends AbstractReadWriteDomain<SummaryDAOImpl, SummaryBean, Long> implements SummaryDomain {

	@Override
	public Collection<PageBean> findPageBySummary(String pathSummary) {
		SummaryBean summary = findSummaryByPath(pathSummary);
		if(summary != null){
			return getDAO().findPageBySummary(summary);
		}
		return null;
	}

	@Override
	public SummaryBean findSummaryByPath(String pathSummary) {
		Criteria<SummaryBean> criteria = new Criteria<SummaryBean>(SummaryBean.class);
		criteria.addProperty("url", pathSummary);
		List<SummaryBean> summaries = (List<SummaryBean>) criteria.executeCriteria();
		if(summaries !=null && !summaries.isEmpty()){
			return summaries.get(0);
		}
		return null;
	}

	@Override
	public Map<SummaryBean, Collection<SummaryBean>> summariesMap() {
		
		Map<SummaryBean, Collection<SummaryBean>> summariesMap = new HashMap<SummaryBean, Collection<SummaryBean>>();
		Criteria<SummaryBean> criteria = new Criteria<SummaryBean>(SummaryBean.class);
		List<SummaryBean> allSummaries = (List<SummaryBean>) criteria.executeCriteria();
		for(SummaryBean summaryBean : allSummaries){
			SummaryBean key = summaryBean;
			boolean add = false;
			if(summaryBean.getOwner() != null){
				key = summaryBean.getOwner();
				add = true;
			}
			Collection<SummaryBean> list = summariesMap.get(key);
			if(list == null){
				list = new ArrayList<SummaryBean>();
			}
			if(add){
				list.add(summaryBean);
			}
			if(!key.getTitle().equals("Administration")){
				summariesMap.put(key,list);
			}	
		}
		return summariesMap;
	}
}
